package controller

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"woanju/dao/mysql"
	"woanju/logic"
	"woanju/models"
)

func GuardianHandler(c *gin.Context) {
	//1.参数校验
	p := new(models.ParamGuardianInfo)
	if err := c.ShouldBindJSON(&p); err != nil {
		//请求参数有误，直接返回响应
		zap.L().Error("GuardianInfo with invalid param", zap.Error(err))
		//判断err是不是validator.ValidationErrors类型
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			ResponseError(c, CodeInvalidParam)
			return
		}

		//c.JSON(http.StatusOK, gin.H{
		//	"msg": removeTopStruct(errs.Translate(trans)), //翻译错误
		//})
		ResponseErrorWithMsg(c, CodeInvalidParam, removeTopStruct(errs.Translate(trans)))

		return
	}

	uid, username, err := GetCurrentUser(c)
	if err != nil {
		ResponseError(c, CodeNeedLogin)
		return
	}

	g := &models.Guardian{
		UserID:       uid,
		GuardianName: p.GuardianName,
		Email:        p.Email,
		Phone:        p.Phone,
	}

	//2.业务处理
	new_g, err := logic.GuardianInfo(g, username)
	if err != nil {
		zap.L().Error("user not exist", zap.Error(err))

		if errors.Is(err, mysql.ErrorUserNotExist) {
			ResponseError(c, CodeUserNotExist)
			return
		}
		ResponseError(c, CodeServerBusy)
		return
	}
	//3.返回响应
	ResponseSuccess(c, gin.H{
		"guardian_name": new_g.GuardianName,
		"user_name":     username,
		"guardian_id":   new_g.GuardianID,
		"email":         new_g.Email,
		"phone":         new_g.Phone,
	})
}

func WarnHandler(c *gin.Context) {
	//1.参数校验
	uid, uname, err := GetCurrentUser(c)
	if err != nil {
		ResponseError(c, CodeNeedLogin)
		return
	}

	//2.业务处理
	if err := logic.Warn(uid, uname); err != nil {
		zap.L().Error("logic.Warn(uid) failed", zap.Error(err))
		if errors.Is(err, mysql.ErrorGuardianNotExist) {
			ResponseError(c, CodeGuardianNotExist)
			return
		}
		ResponseError(c, CodeServerBusy)
		return
	}

	//3.返回响应
	ResponseSuccess(c, nil)
}
